package com.molichuxing.gateway.bff.dealer.services.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.utils.*;
import com.molichuxing.gateway.property.DealerStatusEnum;
import com.molichuxing.gateway.property.EmailSubjectEnum;
import com.molichuxing.gateway.property.StoreOperateEnum;
import com.molichuxing.gateway.utils.OpEmailUtil;
import com.molichuxing.gateway.utils.TokenUtil;
import com.molichuxing.services.business.dto.response.OrderScheduleOfflineBizDto;
import com.molichuxing.services.infrastructure.dto.request.create.FenceCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.FenceModifyDto;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.dto.TabDto;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.gateway.bff.dealer.convertor.Convert;
import com.molichuxing.gateway.bff.dealer.entity.request.create.StoreCreateVo;
import com.molichuxing.gateway.bff.dealer.entity.request.modify.StoreModifyStatusVo;
import com.molichuxing.gateway.bff.dealer.entity.request.modify.StoreModifyVo;
import com.molichuxing.gateway.bff.dealer.entity.response.StoreInfoVo;
import com.molichuxing.gateway.bff.dealer.entity.response.StoreVo;
import com.molichuxing.gateway.bff.dealer.services.StoreBffService;
import com.molichuxing.gateway.property.StoreStatusAndVerifyEnum;
import com.molichuxing.services.business.dto.request.create.StockBizCreateDto;
import com.molichuxing.services.business.dto.request.create.StoreBizCreateDto;
import com.molichuxing.services.business.dto.request.modify.StockBizModifyDto;
import com.molichuxing.services.business.dto.request.modify.StoreBizModifyDto;
import com.molichuxing.services.business.dto.response.StoreBizDto;
import com.molichuxing.services.business.dto.response.StoreInfoBizDto;
import com.molichuxing.services.business.service.StockStoreBizService;
import com.molichuxing.services.business.service.StoreBizService;
import com.molichuxing.services.infrastructure.dto.request.create.IovFenceCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.IovFenceModifyDto;
import com.molichuxing.services.infrastructure.dto.request.modify.StoreDetailModifyDto;

/**
 * 门店信息相关bff
 *
 * @author zhaopenghui
 * @date 2019年8月26日
 */
@Service("storeBffService")
public class StoreBffServiceImpl implements StoreBffService {
    private static final Logger logger = LoggerFactory.getLogger(StoreBffServiceImpl.class);

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private StoreBizService storeBizService;
    @Resource
    private StoreService storeService;
    @Resource
    private StoreDetailService storeDetailService;
    @Resource
    private RegionService regionService;
    @Resource
    StockStoreBizService stockStoreBizService;
    @Resource
    VehicleMakeService vehicleMakeService;
    @Resource
    IovFenceService iovFenceService;
    @Value("${store.fence.width}")
    private String STORE_FENCE_WIDTH;
    @Resource
    private DealerService dealerService;

    @Value("${email_account}")
    private String emailAccount;

    @Value("${email_password}")
    private String emailPassword;

    @Value("${store.check.url}")
    private String storeCheckUrl;

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private RiskEmailService riskEmailService;

    @Resource
    StockStoreService stockStoreService;

    @Resource
    CarService carService;

    @Resource
    FenceStoreStockService fenceStoreStockService;

    /**
     * 门店分页列表
     *
     * @param params
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public Paged<StoreVo> getStorePage(Map<String, Object> params, Integer pageNum, Integer pageSize) throws Exception {
        Integer dealerId = ObjectCastUtil.castInteger(params.get("dealerId"));
        Paged<StoreBizDto> storePage = storeBizService.getStorePage(params, pageNum, pageSize);
        List<StoreBizDto> storeBizDtoList = storePage.getList();
        if (null == storeBizDtoList) {
            Paged<StoreVo> paged = new Paged<StoreVo>();
            return getPageTab(paged, dealerId);
        }

        List<Integer> regionIdList = new ArrayList<>();
        List<Integer> storeIdList = new ArrayList<>();
        for (StoreBizDto storeBizDto : storeBizDtoList) {
            Integer regionId = storeBizDto.getRegionId();
            Integer storeId = storeBizDto.getStoreId();
            regionIdList.add(regionId);
            storeIdList.add(storeId);
        }

        Map<Integer, RegionInfoDto> regionInfoMap = regionService.getRegionInfoListByIds(regionIdList);
        Map<Integer, Integer> carCountMap = getCarCount(storeIdList);

        List<StoreVo> storeVoList = Convert.toStoreVoList(storeBizDtoList, regionInfoMap, carCountMap);
        Paged<StoreVo> paged = new Paged<StoreVo>(storeVoList, storePage.getTotal(), pageSize);
        return getPageTab(paged, dealerId);
    }

    /**
     * 获取分页tab值
     *
     * @return
     * @throws Exception
     */
    private Paged<StoreVo> getPageTab(Paged<StoreVo> paged, Integer dealerId) throws Exception {

        Map<Integer, Integer> statusCountMap = storeService.getStoreCountByStatus(dealerId);
        Map<Integer, Integer> verifyStatusCountMap = storeService.getStoreCountByVerifyStatus(dealerId);
        Integer allCount = storeService.getCount(dealerId);

        List<TabDto> tabList = new ArrayList<>();
        for (StoreStatusAndVerifyEnum storeStatusAndVerifyEnum : StoreStatusAndVerifyEnum.values()) {
            int value = storeStatusAndVerifyEnum.getValue();
            String name = storeStatusAndVerifyEnum.getName();

            Integer count = 0;
            if (StoreStatusAndVerifyEnum.ALL.getValue() == value) {
                count = allCount;
            } else if (StoreStatusAndVerifyEnum.UN_VERIFY.getValue() == value
                    && null != verifyStatusCountMap
                    && verifyStatusCountMap.size() > 0) {
                count = verifyStatusCountMap.get(StoreVerifyStatusEnum.UN_VERIFY.getValue());
            } else if (StoreStatusAndVerifyEnum.VERIFY_REJECT.getValue() == value
                    && null != verifyStatusCountMap
                    && verifyStatusCountMap.size() > 0) {
                count = verifyStatusCountMap.get(StoreVerifyStatusEnum.VERIFY_REJECT.getValue());
            } else if (StoreStatusAndVerifyEnum.OPEN.getValue() == value
                    && null != statusCountMap
                    && statusCountMap.size() > 0) {
                count = statusCountMap.get(StoreStatusEnum.OPEN.getValue());
            } else if (StoreStatusAndVerifyEnum.SUSPENSION.getValue() == value
                    && null != statusCountMap
                    && statusCountMap.size() > 0) {
                count = statusCountMap.get(StoreStatusEnum.SUSPENSION.getValue());
            }

            if (null == count) {
                count = 0;
            }

            TabDto tabDto = new TabDto();
            tabDto.setName(name);
            tabDto.setType(value);
            tabDto.setCount(count);
            tabList.add(tabDto);
        }
        return paged.setTab(tabList);
    }


    private Map<Integer, Integer> getCarCount(List<Integer> storeIdList) throws Exception {
        if (null == storeIdList || storeIdList.size() < 1) {
            return null;
        }
        Map<Integer, StockStoreDto> stockStoreMap = stockStoreService.getStockStoresByStoreIds(storeIdList);
        if (null == stockStoreMap || stockStoreMap.size() < 1) {
            return null;
        }

        List<Integer> stockIdList = stockStoreMap.values().stream().map(StockStoreDto::getStockId).collect(Collectors.toList());
        Map<Integer, Integer> carSumMap = carService.getCarSumByStock(stockIdList, CarsStockTypeEnum.STORE);
        if (null == carSumMap || carSumMap.size() < 1) {
            return null;
        }
        Map<Integer, Integer> carCountMap = new HashMap<>();
        stockStoreMap.forEach((k, v) -> {
            Integer stockId = v.getStockId();
            Integer count = carSumMap.get(stockId);
            carCountMap.put(k, count);
        });

        return carCountMap;
    }

    /**
     * 编辑门店
     *
     * @param storeModifyVo
     * @return
     * @throws Exception
     */
    @Override
    public Boolean modifyStore(StoreModifyVo storeModifyVo) throws Exception {
        validateDealerSuspensionStatus(storeModifyVo.getStoreId(), StoreOperateEnum.MODIFY); //验证经销商是否为暂停营业状态，如果是则抛出异常
        StoreBizModifyDto storeBizModifyDto = Convert.toStoreBizModifyDto(storeModifyVo);
        BigDecimal fenceWidth = new BigDecimal(STORE_FENCE_WIDTH);
        storeBizModifyDto.setFenceWidth(fenceWidth);
        storeBizModifyDto.setFenceShape(StoreDetailFenceShapeEnum.CIRCLE.getValue());
        Boolean aBoolean = storeBizService.modifyStore(storeBizModifyDto);
        if (!aBoolean) {
            return false;
        }
        StockBizModifyDto stockBizModifyDto = Convert.toStockBizModifyDto(storeModifyVo);
        return stockStoreBizService.modify(stockBizModifyDto);
    }


    /**
     * 编辑门店营业状态
     *
     * @param storeModifyStatusVo
     * @return
     * @throws Exception
     */
    @Override
    public Boolean modifyStoreStatus(StoreModifyStatusVo storeModifyStatusVo) throws Exception {
        Integer storeId = storeModifyStatusVo.getStoreId();
        Integer status = storeModifyStatusVo.getStatus();
        if (status == StoreStatusEnum.OPEN.getValue()) { //如果修改状态为营业中状态，判断所属经销商是否为暂停营业状态，如果是则结束流程
            validateDealerSuspensionStatus(storeId, StoreOperateEnum.RE_OPEN);
        }

        Boolean result = storeBizService.modifyStoreStatus(storeId, status, StoreStatusModifyTypeEnum.OP.getValue());
        if (status == StoreStatusEnum.OPEN.getValue() && result) {
            StoreDto storeDto = storeService.getStoreById(storeId);
            List<RiskEmailDto> riskEmailDtos = riskEmailService.getByType(15, RiskEmailReceiveTypeEnum.EMAIL_RECIPIENT.getValue());
            if (riskEmailDtos != null && !riskEmailDtos.isEmpty()) {
                List<String> list = new ArrayList<>();
                for (RiskEmailDto dto : riskEmailDtos) {
                    list.add(dto.getEmail());
                }
                EmailUtil.sendMail(emailAccount, emailPassword, "门店入驻待审核", EmailSubjectEnum.STORE_ENTRY_REVIEWED.getName().replace("$【storeName】", storeDto.getShortName()), tokenUtil.getUser().getAccount());
            }
            DingTalkUtil.execute(storeCheckUrl, EmailSubjectEnum.STORE_ENTRY_REVIEWED.getName().replace("$【storeName】", storeDto.getShortName()));
        }

        return result;
    }

    /**
     * 新增门店
     *
     * @param storeCreateVo
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createStore(StoreCreateVo storeCreateVo) throws Exception {
        StoreBizCreateDto storeBizCreateDto = Convert.toStoreBizCreateDto(storeCreateVo);
        BigDecimal fenceWidth = new BigDecimal(STORE_FENCE_WIDTH);
        storeBizCreateDto.setFenceWidth(fenceWidth);
        storeBizCreateDto.setFenceShape(StoreDetailFenceShapeEnum.CIRCLE.getValue());
        Integer storeId = storeBizService.createStore(storeBizCreateDto);
        if (null == storeId) {
            return false;
        }

        StockBizCreateDto stockBizCreateDto = Convert.toStockBizCreateDto(storeCreateVo);
        stockBizCreateDto.setStoreId(storeId);
        Boolean result = stockStoreBizService.create(stockBizCreateDto);
        if (result) {
            List<RiskEmailDto> riskEmailDtos = riskEmailService.getByType(15, RiskEmailReceiveTypeEnum.EMAIL_RECIPIENT.getValue());
            if (riskEmailDtos != null && !riskEmailDtos.isEmpty()) {
                List<String> list = new ArrayList<>();
                for (RiskEmailDto dto : riskEmailDtos) {
                    list.add(dto.getEmail());
                }
                EmailUtil.sendMail(emailAccount, emailPassword, "门店入驻待审核", EmailSubjectEnum.STORE_ENTRY_REVIEWED.getName().replace("$【storeName】", storeCreateVo.getShortName()), list);
            }
            DingTalkUtil.execute(storeCheckUrl, EmailSubjectEnum.STORE_ENTRY_REVIEWED.getName().replace("$【storeName】", storeCreateVo.getShortName()));
        }
        return result;
    }

    /**
     * 添加围栏
     *
     * @param storeDto
     * @param storeDetailDto
     * @return
     * @throws Exception
     */
    private Integer addIovFence(StoreDto storeDto, StoreDetailDto storeDetailDto) throws Exception {
        String shortName = storeDto.getShortName();
        String address = storeDetailDto.getAddress();
        Integer regionId = storeDto.getRegionId();
        String longitude = storeDetailDto.getLongitude();
        String dimension = storeDetailDto.getDimension();

        String regionAddress = getRegionAddress(regionId);
        if (StringUtils.isNotBlank(regionAddress)) {
            address = regionAddress + address;
        }

        IovFenceCreateDto iovFenceCreateDto = new IovFenceCreateDto();
        iovFenceCreateDto.setFenceName(shortName);
        iovFenceCreateDto.setFenceArea(address);
        iovFenceCreateDto.setAlarmType(IovFenceAlarmTypeEnum.OUT.getValue());
        iovFenceCreateDto.setFenceShape(IovFenceShapeEnum.CIRCLE.getValue());
        iovFenceCreateDto.setRadius(DateTypeUtil.strCastDouble(STORE_FENCE_WIDTH));
        iovFenceCreateDto.setLatitude(DateTypeUtil.strCastDouble(dimension));
        iovFenceCreateDto.setLongitude(DateTypeUtil.strCastDouble(longitude));
        return iovFenceService.addFence(iovFenceCreateDto);
    }


    /**
     * 修改围栏
     *
     * @param storeDto
     * @param storeDetailDto
     * @return
     * @throws Exception
     */
    private Boolean modifyIovFence(StoreDto storeDto, StoreDetailDto storeDetailDto) throws Exception {
        String shortName = storeDto.getShortName();
        String address = storeDetailDto.getAddress();
        Integer regionId = storeDto.getRegionId();
        String longitude = storeDetailDto.getLongitude();
        String dimension = storeDetailDto.getDimension();

        String regionAddress = getRegionAddress(regionId);
        if (StringUtils.isNotBlank(regionAddress)) {
            address = regionAddress + address;
        }
        Integer fenceId = storeDetailDto.getFenceId();

        IovFenceModifyDto iovFenceDto = new IovFenceModifyDto();
        iovFenceDto.setId(DateTypeUtil.integerCastLong(fenceId));
        iovFenceDto.setFenceName(shortName);
        iovFenceDto.setFenceArea(address);
        iovFenceDto.setAlarmType(IovFenceAlarmTypeEnum.OUT.getValue());
        iovFenceDto.setFenceShape(IovFenceShapeEnum.CIRCLE.getValue());
        iovFenceDto.setRadius(DateTypeUtil.strCastDouble(STORE_FENCE_WIDTH));
        iovFenceDto.setLatitude(DateTypeUtil.strCastDouble(dimension));
        iovFenceDto.setLongitude(DateTypeUtil.strCastDouble(longitude));
        return iovFenceService.modifyFence(iovFenceDto);
    }


    /**
     * 删除围栏
     *
     * @param fenceId
     * @return
     * @throws Exception
     */
    private Boolean daletefence(Integer fenceId) throws Exception {
        return iovFenceService.deleteFence(fenceId);
    }

    /**
     * 门店审核
     *
     * @param storeId
     * @param verifyStatus
     * @param rejectReason
     * @param remark
     * @return
     * @throws Exception
     */
    @Override
    public Boolean modifyStoreVerifyStatus(Integer storeId, Integer verifyStatus, String rejectReason, String remark) throws Exception {
        Assert.notNull(storeId, "门店审核失败");
        Assert.notNull(verifyStatus, "门店审核失败");

        StoreDto storeDto = storeService.getStoreById(storeId);
        Assert.notNull(storeDto, "门店不存在");

        validateDealerSuspensionStatus(storeId, StoreOperateEnum.VERIFY); //验证经销商是否为暂停营业状态

        Integer oldFenceId = null;
        Integer fenceId = null;
        if (StoreVerifyStatusEnum.VERIFY_PASS.getValue() == verifyStatus) {
            StoreDetailDto storeDetailDto = storeDetailService.getStoreDetailById(storeId);
            oldFenceId = storeDetailDto.getFenceId();
            fenceId = addOrModifyFence(storeDto, storeDetailDto);
        }

        Boolean modifyStoreBoolean = storeBizService.modifyStoreVerifyStatus(storeId, verifyStatus, rejectReason, remark);
        if (!modifyStoreBoolean && StoreVerifyStatusEnum.VERIFY_PASS.getValue() == verifyStatus && null == oldFenceId && fenceId != null) {
            daletefence(fenceId);
            unBingingFence(storeId, fenceId);
        }
        List<String> list = null;
        List<RiskEmailDto> riskEmailDtos = riskEmailService.getByType(15, RiskEmailReceiveTypeEnum.EMAIL_RECIPIENT.getValue());
        if (riskEmailDtos != null && !riskEmailDtos.isEmpty()) {
            list = new ArrayList<>();
            for (RiskEmailDto dto : riskEmailDtos) {
                list.add(dto.getEmail());
            }
        }
        if ((modifyStoreBoolean) && (StoreVerifyStatusEnum.VERIFY_PASS.getValue() == verifyStatus)) {
            if (null != list) {
                EmailUtil.sendMail(emailAccount, emailPassword, "门店入驻通过审核", EmailSubjectEnum.STORE_PASSED_EXAMINATION.getName().replace("$【storeName】", storeDto.getShortName()), list);
            }
        }
        if ((modifyStoreBoolean) && (StoreVerifyStatusEnum.VERIFY_REJECT.getValue() == verifyStatus)) {
            if (null != list) {
                EmailUtil.sendMail(emailAccount, emailPassword, "门店入驻驳回审核", EmailSubjectEnum.STORE_REJECTION_REVIEW.getName().replace("$【storeName】", storeDto.getShortName()), list);
            }
        }
        return modifyStoreBoolean;
    }

    /**
     * 绑定围栏
     *
     * @param storeId
     * @param fenceId
     * @return
     * @throws Exception
     */
    private Boolean bingingFence(Integer storeId, Integer fenceId) throws Exception {
        List<Integer> fenceIdList = new ArrayList<>();
        fenceIdList.add(fenceId);

        FenceCreateDto fenceCreateDto = new FenceCreateDto();
        fenceCreateDto.setStoreId(storeId);
        fenceCreateDto.setType(FenceStoreStockTypeEnum.STORE.getValue());
        fenceCreateDto.setFenceIdList(fenceIdList);
        return fenceStoreStockService.createFence(fenceCreateDto);
    }

    /**
     * 解绑围栏
     *
     * @param storeId
     * @param fenceId
     * @return
     * @throws Exception
     */
    private Boolean unBingingFence(Integer storeId, Integer fenceId) throws Exception {
        FenceModifyDto fenceModifyDto = new FenceModifyDto();
        fenceModifyDto.setStoreId(storeId);
        fenceModifyDto.setType(FenceStoreStockTypeEnum.STORE.getValue());
        fenceModifyDto.setFenceId(fenceId);
        return fenceStoreStockService.deleteFence(fenceModifyDto);
    }

    /**
     * 添加修改围栏
     *
     * @param storeDto
     * @param storeDetailDto
     * @return
     * @throws Exception
     */
    private Integer addOrModifyFence(StoreDto storeDto, StoreDetailDto storeDetailDto) throws Exception {
        Integer oldFenceId = storeDetailDto.getFenceId();
        Integer storeId = storeDetailDto.getStoreId();
        if (null == oldFenceId) {
            Integer fenceId = addFence(storeDto, storeDetailDto);
            bingingFence(storeId, fenceId);
            return fenceId;
        } else {
            IovFenceDto iovFenceDto = iovFenceService.getFenceById(oldFenceId);
            if (null == iovFenceDto) {
                Integer fenceId = addFence(storeDto, storeDetailDto);
                bingingFence(storeId, fenceId);
                return fenceId;
            } else {
                Integer fenceId = modifyFence(storeDto, storeDetailDto);
                return fenceId;
            }
        }
    }

    private Integer addFence(StoreDto storeDto, StoreDetailDto storeDetailDto) throws Exception {
        Integer fenceId = addIovFence(storeDto, storeDetailDto);
        if (null == fenceId) {
            throw new BizException("车联网创建围栏失败");
        }
        StoreDetailModifyDto storeDetailModifyDto = new StoreDetailModifyDto();
        storeDetailModifyDto.setStoreId(storeDto.getStoreId());
        storeDetailModifyDto.setFenceId(fenceId);
        Boolean modifyStoreBoolean = storeDetailService.modifyStoreDetail(storeDetailModifyDto);
        if (!modifyStoreBoolean) {
            daletefence(fenceId);
        }
        return fenceId;
    }

    private Integer modifyFence(StoreDto storeDto, StoreDetailDto storeDetailDto) throws Exception {
        Boolean modifyFenceBoolean = modifyIovFence(storeDto, storeDetailDto);
        if (!modifyFenceBoolean) {
            throw new BizException("车联网编辑围栏失败");
        }
        return storeDetailDto.getFenceId();
    }

    /**
     * 获取门店详情
     *
     * @param storeId
     * @return
     */
    @Override
    public StoreInfoVo getStoreInfo(Integer storeId) throws Exception {
        StoreInfoBizDto storeInfo = storeBizService.getStoreInfo(storeId);
        StoreInfoVo storeInfoVo = Convert.toStoreInfoVo(storeInfo);

        Integer brandId = storeInfo.getBrandId();
        Integer regionId = storeInfo.getRegionId();
        if (brandId != null) {
            VehicleMakeDto vehicleMakeDto = vehicleMakeService.getVehicleMakeDtoById(brandId);
            if (vehicleMakeDto != null) {
                storeInfoVo.setBrandName(vehicleMakeDto.getName());
            }
        }

        String regionAddress = getRegionAddress(regionId);
        if (StringUtils.isNotBlank(regionAddress)) {
            String address = storeInfoVo.getAddress();
            storeInfoVo.setDetailAddress(regionAddress + address);
        }

        RegionInfoDto regionInfoDto = regionService.getCityNameByCityId(regionId);
        if (regionInfoDto != null) {
            String provinceName = regionInfoDto.getProvinceFullName();
            String cityName = regionInfoDto.getCityFullName();
            Integer provinceId = regionInfoDto.getProvinceId();
            storeInfoVo.setProvinceId(provinceId);
            storeInfoVo.setProvinceName(provinceName);
            storeInfoVo.setCityName(cityName);
        }

        return storeInfoVo;
    }

    /**
     * 获取地址
     *
     * @param regionId
     * @return
     */
    private String getRegionAddress(Integer regionId) {
        String returnStr = "";
        if (null == regionId) {
            return "";
        }

        RegionInfoDto regionInfoDto = regionService.getCityNameByCityId(regionId);
        if (null == regionInfoDto) {
            return "";
        }

        String provinceName = regionInfoDto.getProvinceFullName();
        String cityName = regionInfoDto.getCityFullName();
        if (StringUtils.isNotBlank(provinceName)) {
            returnStr = returnStr + provinceName;
        }
        if (StringUtils.isNotBlank(cityName)) {
            returnStr = returnStr + cityName;
        }
        return returnStr;
    }


    /**
     * 获取门店信息
     *
     * @param dealerId 经销商id
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<StoreVo> getStoreByDealerId(Integer dealerId) {
        List<StoreVo> result = null;
        // redis中获取
        // String redisKey = RedisKeyConst.DEALER_STORE_DEALER + dealerId;
        // String stores = redisUtil.get(redisKey);
        // if (StringUtils.isNotBlank(stores)) {
        // // 存在
        // return JSONObject.parseObject(stores, List.class);
        // }
        // 根据经销商id查询门店id
        List<StoreDto> storeDtos = storeService.getByDealer(dealerId);
        if (storeDtos == null || storeDtos.isEmpty()) {
            return result;
        }
        result = Convert.toStoreVo(storeDtos);
        // 存入redis
        // redisUtil.set(redisKey, JSONObject.toJSONString(result));
        return result;
    }


    /**
     * 获取营业中门店信息
     *
     * @param dealerId 经销商id
     * @return
     */
    @Override
    public List<StoreVo> getOpenStoreByDealerId(Integer dealerId) {
        List<StoreVo> result = null;
        // 根据经销商id查询门店id
        Map<String, Object> map = new HashMap<>();
        map.put("dealerId", dealerId);
        List<StoreDto> storeDtos = storeService.getStoreList(map);
        if (storeDtos == null || storeDtos.isEmpty()) {
            return result;
        }
        result = Convert.toStoreVo(storeDtos);
        return result;
    }

    /**
     * 验证经销商是否为暂停营业状态，如果是则抛出异常
     */
    private void validateDealerSuspensionStatus(Integer storeId, StoreOperateEnum type) throws Exception {
        StoreDto store = storeService.getStoreById(storeId);
        if (store != null && store.getDealerId() != null && store.getDealerId() > 0) {
            DealerDto dealer = dealerService.getDealerById(store.getDealerId());
            if (dealer != null && dealer.getStatus() == DealerStatusEnum.SUSPENSION.getValue()) {
                throw new BizException(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "经销商已暂停营业，不允许" + type.getName());
            }
        }
    }

    /**
     * 创建门店围栏
     *
     * @return
     * @throws Exception
     */
    @Override
    public Boolean createStoreFence() throws Exception {
        List<StoreDto> allStoreList = storeService.getAllStoreList(null);
        if (null == allStoreList || allStoreList.size() < 1) {
            throw new BizException("没有营业中门店");
        }

        List<Integer> storeIdList = new ArrayList<>();
        for (StoreDto storeDto : allStoreList) {
            Integer storeId = storeDto.getStoreId();
            if (null == storeId) {
                continue;
            }

            storeIdList.add(storeId);
        }

        Map<Integer, StoreDetailDto> storeDetailMap = storeDetailService.getStoreDetailMapByIds(storeIdList);
        if (null == storeDetailMap || storeDetailMap.size() < 1) {
            throw new BizException("门店不存在");
        }
        for (StoreDto storeDto : allStoreList) {
            Integer storeId = storeDto.getStoreId();
            if (null == storeId) {
                continue;
            }

            StoreDetailDto storeDetailDto = storeDetailMap.get(storeId);
            if (null == storeDetailDto) {
                continue;
            }
            String longitude = storeDetailDto.getLongitude();
            String dimension = storeDetailDto.getDimension();
            Integer fenceId = storeDetailDto.getFenceId();
            if (null == fenceId && StringUtils.isNoneBlank(longitude) && StringUtils.isNoneBlank(dimension)) {
                addOrModifyFence(storeDto, storeDetailDto);
            }
        }
        return true;
    }


}
